package com.cn.yang.util;//package com.cn.yang.util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class MyFilter implements Filter {
   @Override
   public void init(FilterConfig filterConfig) throws ServletException {
   }

   @Override
   public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
       HttpServletRequest req = (HttpServletRequest) servletRequest;
       HttpServletResponse resp = (HttpServletResponse) servletResponse;
       req.setCharacterEncoding("UTF-8");
       resp.setCharacterEncoding("UTF-8");
//       resp.setHeader("Access-Control-Allow-Origin", "http://localhost:63343");
//       resp.setHeader("Access-Control-Allow-Credentials", "true");

       resp.setContentType("application/json;charset=utf-8");

       /* 允许跨域的主机地址 */
       resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
       /* 允许跨域的请求方法GET, POST, HEAD 等 */
       resp.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
       /* 重新预检验跨域的缓存时间 (s) */
       resp.setHeader("Access-Control-Max-Age", "3600");
       /* 允许跨域的请求头 */
       resp.setHeader("Access-Control-Allow-Headers", "Content-Type , Content-Length , Access-Token , Authorization , Accept , X-Requested-With , X-Custom-Header , Request-Ajax , yourHeaderFeild");
       /* 是否携带cookie */
       resp.setHeader("Access-Control-Allow-Credentials", "true");
       resp.setHeader("XDomainRequestAllowed", "1");
//       if (resp.getMethod().equals("OPTIONS")) {
//           HttpUtil.setResponse(response, HttpStatus.OK.value(), null);
//           return;
//       }

//       String url = req.getServletPath();
//       System.out.println(url);
//       if (url.startsWith("/back/")){
//           if(url.endsWith("css")||url.endsWith("js")||url.endsWith("regester")){
//               filterChain.doFilter(servletRequest,servletResponse);
//           }else {
//
//               String username = (String) req.getSession().getAttribute("username");
//               if (username==null){
//                   // resp.sendRedirect("http://localhost:8066/login.html");
//                   // req.getRequestDispatcher("http://localhost:8066/login.html").forward(req,resp);
//                   resp.getWriter().println(400);
//               }else {
//                   System.out.println("Filter1");
//                   filterChain.doFilter(servletRequest,servletResponse);
//               }
//           }
//       }else {
//           System.out.println("Filter2");
//           filterChain.doFilter(servletRequest,servletResponse);
//       }
        filterChain.doFilter(servletRequest,servletResponse);

   }

   @Override
   public void destroy() {

   }
}
